<template>
    <transition name="fade">
        <div class="back-arrow" @click="goBack" v-show="showBackArrow">
            <el-icon>
                <ArrowLeft />
            </el-icon>
        </div>
    </transition>
    <a href="javascript:void(0)" @click="logout" class="logout-link">
        <el-icon class="logout-icon">
            <SwitchButton />
        </el-icon>
        退出登录[{{ loginName }}]
    </a>
    <!-- 页面标题 -->
    <h4 class="page-title">反馈任务列表</h4>
    <div class="feedback-task-list">
        <div class="container">
            <div class="feedback-container">
                <!-- 左侧垂直表头区域 -->
                <div class="vertical-header">
                    
                    <div class="header-item">反馈用户：</div>
                    <div class="header-item">网格：</div>
                    <div class="header-item">详细地址：</div>
                    <div class="header-item">预估等级：</div>
                    <div class="header-item">信息描述：</div>
                </div>
                <!-- 右侧内容区域 -->
                <div class="content-area">
                    <div class="content-item">{{ form.supervisorName }}</div>
                    <div class="content-item">{{ form.gridProvince }} {{ form.gridCity }}</div>
                    <div class="content-item">{{ form.address }}</div>
                    <div class="content-item">{{ form.estimatedAqiLevel }}</div>
                    <div class="content-item">{{ form.description }}</div>
                </div>
            </div>
            <!-- 浓度录入表单及提交区域 -->
            <div class="form-container">
                <el-form ref="concentrationForm" :model="aqidata" label-width="80px" class="concentration-form">
                    <el-form-item label="SO₂浓度">
                        <div class="form-item-row">
                            <el-input v-model="aqi.so2Level" placeholder="请输入SO₂浓度" class="input-with-unit" />
                            <span class="unit">ug/m³
                            </span>
                            <span v-if="aqi.so2Level >= 0 && aqi.so2Level <= 50">
                                <el-tag color="#52c41a" style="color: #fff;">一</el-tag>
                            </span>
                            <span v-else-if="aqi.so2Level > 50 && aqi.so2Level <= 150">
                                <el-tag color="#a0d911" style="color: #fff;">二</el-tag>
                            </span>
                            <span v-else-if="aqi.so2Level > 150 && aqi.so2Level <= 475">
                                <el-tag color=" #faad14" style="color: #fff;">三</el-tag>
                            </span>
                            <span v-else-if="aqi.so2Level > 475 && aqi.so2Level <= 800">
                                <el-tag color=" #f5222d" style="color: #fff;">四</el-tag>
                            </span>
                            <span v-else-if="aqi.so2Level > 800 && aqi.so2Level <= 1600">
                                <el-tag color="#eb2f96" style="color: #fff;">五</el-tag>
                            </span>
                            <span v-else-if="aqi.so2Level > 1600" >
                                <el-tag color="#722ed1" style="color: #fff;">六</el-tag>
                            </span>
                        </div>
                    </el-form-item>
                    <el-form-item label="CO浓度">
                        <div class="form-item-row">
                            <el-input v-model="aqi.coLevel" placeholder="请输入CO浓度" class="input-with-unit" />
                            <span class="unit">mg/m³
                            </span>
                            <span v-if="aqi.coLevel >= 0 && aqi.coLevel <= 5">
                                <el-tag color="#52c41a" style="color: #fff;">一</el-tag>

                            </span>
                            <span v-else-if="aqi.coLevel > 5 && aqi.coLevel <= 10">
                                <el-tag color="#a0d911" style="color: #fff;">二</el-tag>
                            </span>
                            <span v-else-if="aqi.coLevel > 10 && aqi.coLevel <= 35">
                                <el-tag color=" #faad14" style="color: #fff;">三</el-tag>
                            </span>
                            <span v-else-if="aqi.coLevel > 35 && aqi.coLevel <= 60">
                                <el-tag color=" #f5222d" style="color: #fff;">四</el-tag>

                            </span>
                            <span v-else-if="aqi.coLevel > 60 && aqi.coLevel <= 90">
                                <el-tag color=" #f5222d" style="color: #fff;">五</el-tag>
                            </span>
                            <span v-else-if="aqi.coLevel > 90">
                                <el-tag color="#722ed1" style="color: #fff;">六</el-tag>
                            </span>
                        </div>
                    </el-form-item>
                    <el-form-item label="PM2.5">
                        <div class="form-item-row">
                            <el-input v-model="aqi.pm25Level" placeholder="请输入PM2.5浓度" class="input-with-unit" />
                            <span class="unit">mg/m³
                            </span>
                            <span v-if="aqi.pm25Level >= 0 && aqi.pm25Level <= 35">
                                <el-tag color="#52c41a" style="color: #fff;">一</el-tag>
                            </span>
                            <span v-else-if="aqi.pm25Level > 35 && aqi.pm25Level <= 75">
                                <el-tag color="#a0d911" style="color: #fff;">二</el-tag>
                            </span>
                            <span v-else-if="aqi.pm25Level > 75 && aqi.pm25Level <= 115">
                                <el-tag color=" #faad14" style="color: #fff;">三</el-tag>
                            </span>
                            <span v-else-if="aqi.pm25Level > 115 && aqi.pm25Level <= 150">
                                <el-tag color=" #f5222d" style="color: #fff;">四</el-tag>
                            </span>
                            <span v-else-if="aqi.pm25Level > 150 && aqi.pm25Level <= 250">
                                <el-tag color="#eb2f96" style="color: #fff;">五</el-tag>
                            </span>
                            <span v-else-if="aqi.pm25Level > 250">
                                <el-tag color="#722ed1" style="color: #fff;">六</el-tag>
                            </span>
                        </div>
                    </el-form-item>

                    <!-- 在表单下方或其他合适位置插入 -->
                    <div class="aqi-level">
                        <span>实测AQI等级：</span>
                        <el-tag v-if="actualAqiLevel" :color="getLevelColor(actualAqiLevel)"
                            style="color: #fff; font-weight: bold;">
                            {{ levelTextMap[actualAqiLevel] || '未知' }}
                        </el-tag>
                        <span v-else></span>
                    </div>

                    <el-button type="primary" class="submit-btn" @click="submitForm">
                        提交实测数据
                    </el-button>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElIcon, ElForm, ElFormItem, ElInput, ElTag, ElButton,ElMessage,ElMessageBox } from 'element-plus'
import { ArrowLeft, Menu } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getinformationbyidApi } from '@/api/getinformationByid'
import { applicationApi} from '@/api/application'
import { getWorkerNameApi } from '@/api/getworkername'

const loginName = ref('')
const router = useRouter()

const aqi = ref({
    so2Level :null,
    coLevel:null,
    feedbackId:null,
    pm25Level:null,
}
)
const showBackArrow = ref(false)
const selectedId = localStorage.getItem('selectedId');

onMounted(async() => {
    showBackArrow.value = true
    if (selectedId) {
        console.log('获取到的 id：', selectedId);
        // 后续可根据这个 id 做业务逻辑，比如发请求获取对应详情数据等
    } else {
        console.log('未获取到有效 id');
    }
    query(selectedId);
    try {
        const result = await getWorkerNameApi()
        loginName.value = result.data
    } catch (error) {
        console.error('获取姓名失败:', error)
        ElMessage.error(result.message) 
    }
})
const logout = () => {
    //弹出确认框, 如果确认, 则退出登录, 跳转到登录页面
    ElMessageBox.confirm('确认退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {//确认, 则清空登录信息
        ElMessage.success('退出登录成功')
        localStorage.removeItem('loginUser')
        router.push('/login')//跳转到登录页面
    })
}
const goBack = () => {
    router.push('/feedbacktask')
}
// 表单数据
const form = ref({})
// 计算实际 AQI 等级
// 获取每种污染物的等级（返回 1~6）
const getPollutantLevel = (value, type) => {
    if (value === undefined || value === '' || value === null) {
        return null;
    }

    // 将字符串转为数字
    const val = parseFloat(value);

    switch (type) {
        case 'so2':
            if (val >= 0 && val <= 50) return 1;
            else if (val <= 150) return 2;
            else if (val <= 475) return 3;
            else if (val <= 800) return 4;
            else if (val <= 1600) return 5;
            else return 6;

        case 'co':
            if (val >= 0 && val <= 5) return 1;
            else if (val <= 10) return 2;
            else if (val <= 35) return 3;
            else if (val <= 60) return 4;
            else if (val <= 90) return 5;
            else return 6;

        case 'pm25':
            if (val >= 0 && val <= 35) return 1;
            else if (val <= 75) return 2;
            else if (val <= 115) return 3;
            else if (val <= 150) return 4;
            else if (val <= 250) return 5;
            else return 6;

        default:
            return null;
    }
};

// 计算最高污染等级
const actualAqiLevel = computed(() => {
    const so2Level = getPollutantLevel(aqi.value.so2Level, 'so2');
    const coLevel = getPollutantLevel(aqi.value.coLevel, 'co');
    const pm25Level = getPollutantLevel(aqi.value.pm25Level, 'pm25');

    // 过滤 null 值
    const validLevels = [so2Level, coLevel, pm25Level].filter(level => level !== null);

    // 无有效等级时返回 null
    return validLevels.length ? Math.max(...validLevels) : null;
});
//获取数据
const query = async (id) => {
    const result = await getinformationbyidApi(id)
    console.log(result)
    form.value = result.data
    console.log(result.data)
    console.log(form.value)
};



// 等级文本映射
const levelTextMap = {
    1: '一级 优',
    2: '二级 良',
    3: '三级 轻度污染',
    4: '四级 中度污染',
    5: '五级 重度污染',
    6: '六级 严重污染'
}




// 提交表单
const submitForm = async () => {
    console.log('提交数据：', aqi.value)
    // 可在此处编写接口请求逻辑，如 axios.post(...)
    try {
        aqi.value.feedbackId = selectedId
        console.log(aqi.value)
        const res = await applicationApi(aqi.value)
        console.log(res)
        if (res.code === 200) {
            ElMessage.success('提交成功')
            router.push('/feedbacktask')
        }else {
            ElMessage.error(res.message)
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(res.message)
    }
}


// 获取等级背景色
const getLevelColor = (level) => {
    const colorMap = {
        1: '#52c41a',
        2: '#a0d911',
        3: '#faad14',
        4: '#f5222d',
        5: '#eb2f96',
        6: '#722ed1'
    }
    return colorMap[level] || '#ccc'
}

</script>

<style scoped>
.back-arrow {
    position: absolute;
    left: 18px;
    top: 18px;
    font-size: 20px;
    color: #409eff;
    cursor: pointer;
    transition: all 0.3s;
}

.back-arrow:hover {
    color: #409eff;
    transform: translateX(-3px);
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

.form-item-row {
    display: flex;
    align-items: center;
    /* 垂直居中，让元素在一行更整齐 */
    gap: 5px;
}

/* 去掉 a 标签下划线、设置白色 */
.logout-link {
    text-decoration: none;
    position: absolute;
    font-size: 14px;
    font-family: 楷体;
    top: 25px;
    right: 10px;
    cursor: pointer;
    margin-bottom: 20px;
    color: rgb(13, 124, 228);
    padding-top: -10px;
    border-radius: 4px;
    transition: all 0.3s ease;
}

/* 页面标题样式 */
.page-title {
    text-align: center;
    margin: 0 auto;
    margin-top: 12px;
}

/* 提交按钮样式 */
.submit-btn {
    width: 100%;
    max-width: 200px;
    margin: 0 auto;
    display: block;
}

/* 表单容器样式 */
.form-container {
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    box-sizing: border-box;
}

/* 输入框与单位、等级标签样式 */
.input-with-unit {
    width: 70%;
    margin-right: 8px;
}

/* // 反馈任务容器样式 */
.feedback-container {
    display: flex;
    width: 90%;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(6, 130, 207, 0.1);
    margin: 20px auto;
    /* font-family: 楷体; */
    font-size: 16px;
}

/* 左侧垂直表头 */
.vertical-header {
    width: 100px;
    background-color: #f8f9fa;
    display: flex;
    flex-direction: column;
}

/* // 表头项 */
.header-item {
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #ebeef5;
    font-weight: bold;
    font-size: 12px;
    color: #999;
}

/* 右侧内容区域 */
.content-area {
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* // 内容项 */
.content-item {
    height: 32px;
    font-size: 10px;
    color: #999;
    display: flex;
    align-items: center;
    padding-left: 20px;
    border-bottom: 1px solid #ebeef5;
}



/* 页面整体样式 */
.feedback-task-list {
    width: 100%;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: url('@/assets/1.png') no-repeat center/cover;
    position: relative;
    padding-top: 100px;
    margin-top: 15px;
    box-sizing: border-box;
}

/* 内容容器样式 
   修改 max-width 让容器更宽，比如从 400px 改到 600px ，也可根据需求调整为更大值或去掉 max-width 直接用 width: 90%; 自适应 */
.container {
    width: 97%;
    /* 调整最大宽度，让容器更宽 */
    max-width: 600px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    box-sizing: border-box;
    margin-top: 80px;
}


/* // input */
.unit {
    line-height: 32px;
    color: #999;
}


/* // aqi */
.aqi-level {
    margin-top: 20px;
    margin-bottom: 20px;
    text-align: center;
}

.level-text {
    padding: 5px 10px;
    color: #fff;
    font-weight: bold;
}
</style>